package com.example.synccenter.identitysource.processor;

import com.example.synccenter.entity.SyncTaskEntity;
import com.example.synccenter.service.SyncTaskService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * 默认身份源事件后处理器，实现事件数据的同步后处理逻辑。
 */
@Slf4j
@Component
public class DefaultIdentitySourceEventPostProcessor extends AbstractIdentitySourcePostProcessor {
    @Autowired
    private SyncTaskService syncTaskService;

    /**
     * 构造方法，指定处理器名称
     */
    public DefaultIdentitySourceEventPostProcessor() {
        super("事件后处理器");
    }

    /**
     * 实现事件数据的具体处理逻辑
     * @param data 事件数据
     * @param context 同步上下文
     */
    @Override
    protected void doProcess(Map<String, Object> data, Map<String, Object> context) {
        // 从上下文中获取必要信息
        String eventType = (String) data.get("eventType");
        String sourceType = (String) context.get("sourceType");
        String sourceId = StringUtil.isEmpty((String) context.get("sourceId")) ? "source-id" : (String) context.get("sourceId");

        log.info("处理{}身份源事件: {}", sourceType, eventType);

        try {
            LocalDateTime now = LocalDateTime.now();
            // 写入同步任务记录
            SyncTaskEntity task = new SyncTaskEntity();
            task.setId(UUID.randomUUID().toString());
            task.setSourceId(sourceId);
            task.setTriggerType("事件");
            task.setStartTime(now);
            task.setEndTime(now);
            task.setStatus("成功");
            task.setErrorMessage(null);
            task.setDuration(0L);
            syncTaskService.save(task);
            log.info("{}身份源事件同步任务保存成功: {}", sourceType, eventType);
        } catch (Exception e) {
            log.error("{}身份源事件同步任务保存失败: {}", sourceType, e.getMessage(), e);
            throw e;
        }
    }
} 